package com.unis.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.CryptoUtil;
import com.unis.common.util.StrUtil;
import com.unis.common.util.TemplateUtil;
import com.unis.dto.ResultDto;
import com.unis.service.impl.BaseServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.mapper.system.AccountMapper;
import com.unis.model.system.Account;
import com.unis.service.system.AccountService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see AccountService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2018-12-27
 */
@Service("accountService")
public class AccountServiceImpl extends BaseServiceImpl implements AccountService {
	private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
    @Autowired
    private AccountMapper accountMapper;

    /**
     * @see AccountService#insert(Account account)
     */
    @Override
    public int insert(Account account) throws Exception {
    	if (account!=null){
			//getPrimaryKey("SEQ_T_SYS_ACCOUNT_PK",account.getJgdm(),"YH");
			account.setPk(TemplateUtil.genUUID());
			account.setSalt(CryptoUtil.getRandomSalt());
			if (!StringUtils.isNotBlank(account.getPassword())){
				account.setPassword("123456");
			}
			String password = CryptoUtil.encodePassphrase(account.getPassword(), account.getSalt());
			account.setPassword(password);
			account.setZt("1");
			//account.setJgmc(account.getJgdm());//机构名称翻译
	        return accountMapper.insertSelective(account);
    	}else{
    		logger.error("AccountServiceImpl.insert时account数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.insert时account数据为空。");
    	}        
    }

    /**
     * @see AccountService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("AccountServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("AccountServiceImpl.delete时pk为空。");
    	}else{
    		//return accountMapper.deleteByPrimaryKey(pk);
			Account account = new Account();
			account.setPk(pk);
			account.setZt("0");
			return this.updateByPrimaryKey(account);
    	}
    }

    /**
     * @see AccountService#updateByPrimaryKey(Account account)
     */
    @Override
    public int updateByPrimaryKey(Account account) throws Exception {
        if (account!=null){
        	if(StringUtils.isBlank(account.getPk())){
        		logger.error("AccountServiceImpl.updateByPrimaryKey时account.Pk为空。");
        		throw new AppRuntimeException("AccountServiceImpl.updateByPrimaryKey时account.Pk为空。");
        	}
			if (StringUtils.isNotBlank(account.getPassword())){
				account.setSalt(CryptoUtil.getRandomSalt());
				String password = CryptoUtil.encodePassphrase(account.getPassword(), account.getSalt());
				account.setPassword(password);
			}
	        return accountMapper.updateByPrimaryKeySelective(account);
    	}else{
    		logger.error("AccountServiceImpl.updateByPrimaryKey时account数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.updateByPrimaryKey时account数据为空。");
    	}
    }

	@Override
	public String changePwd(String old_password, String password, String conf_password) throws Exception {
    	String msg = "";
		if (StringUtils.isBlank(old_password) || StringUtils.isBlank(password) || StringUtils.isBlank(conf_password)){
			msg = "信息填写不完整，请重新输入";
			return msg;
		}
		UserInfo userInfo = this.getUserInfo();
		String old_password_encode = CryptoUtil.encodePassphrase(old_password, userInfo.getSalt());
		if (!StringUtils.equals(old_password_encode,userInfo.getPassword())){
			msg="旧密码输入有误，请重新输入";
			return msg;
		}
		if(!StringUtils.equals(password,conf_password)){
			msg="两次密码输入不一致，请重新输入";
			return msg;
		}

		Account account = new Account();
		account.setPk(userInfo.getPk());
		account.setSalt(CryptoUtil.getRandomSalt());
		String new_password = CryptoUtil.encodePassphrase(password, account.getSalt());
		account.setPassword(new_password);
		accountMapper.updateUserPwd(account);
		msg = "密码修改成功";
		return msg;
	}

	@Override
	public int resetPwdByInfo() throws Exception {
    	UserInfo userInfo = this.getUserInfo();
		Account account = new Account();
		account.setPk(userInfo.getPk());
		account.setSalt(CryptoUtil.getRandomSalt());
		if (StringUtils.isNotBlank(userInfo.getJh())){
			account.setPassword(userInfo.getJh());
		}else{
			account.setPassword("123456");
		}
		String password = CryptoUtil.encodePassphrase(account.getPassword(), account.getSalt());
		account.setPassword(password);
		accountMapper.updateUserPwd(account);
		return 1;
	}

	/**
     * @see AccountService#queryAccountByPrimaryKey(String pk)
     */
    @Override
    public Account queryAccountByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("AccountServiceImpl.queryAccountByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("AccountServiceImpl.queryAccountByPrimaryKey时pk为空。");
    	}else{
    		return accountMapper.selectByPrimaryKey(pk);
    	}
    }
    
    
    /**
     * @see AccountService#queryAsObject(Account account)
     */
    @Override
    public Account queryAsObject(Account account) throws Exception {
        if (account!=null){
	        return accountMapper.selectOne(account);
    	}else{
    		logger.error("AccountServiceImpl.queryAsObject时account数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.queryAsObject时account数据为空。");
    	}
    }
    
    /**
     * @see AccountService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return accountMapper.selectCountByExample(example);
    	}else{
    		logger.error("AccountServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see AccountService#queryListByExample(Example example)
     */
    @Override
    public List<Account> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return accountMapper.selectByExample(example);
    	}else{
    		logger.error("AccountServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see AccountService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(accountMapper.selectByExample(example));
    	}else{
    		logger.error("AccountServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("AccountServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }
	@Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
    	if (parmMap!=null){
			Example example = new Example(Account.class);
			example.setOrderByClause("rksj DESC,pk asc");
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("zt",1);

			//对于系统管理员用户进行屏蔽，如果是非_SYSTEMADMIN用户，查询不出_SYSTEMADMIN用户
			Subject subject = SecurityUtils.getSubject();
			if (!subject.hasRole("_SYSTEMADMIN")){
				criteria.andNotEqualTo("pk","61e8b130a161435aab7a3f549eee9f46");
			}

			if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
			}
			if(parmMap.get("idno")!=null && StringUtils.isNotBlank(parmMap.get("idno").toString())){
				criteria.andEqualTo("idno",parmMap.get("idno").toString().trim());
			}
			if(parmMap.get("username")!=null && StringUtils.isNotBlank(parmMap.get("username").toString())){
				criteria.andEqualTo("username",parmMap.get("username").toString().trim());
			}
			if(parmMap.get("isAdmin")!=null &&StringUtils.isNotBlank(parmMap.get("isAdmin").toString())){
				criteria.andEqualTo("isAdmin",parmMap.get("isAdmin").toString().trim());
			}
			if(parmMap.get("xm")!=null && StringUtils.isNotBlank(parmMap.get("xm").toString())){
				criteria.andEqualTo("xm",parmMap.get("xm").toString().trim());
			}
			if(parmMap.get("jh")!=null && StringUtils.isNotBlank(parmMap.get("jh").toString())){
				criteria.andEqualTo("jh",parmMap.get("jh").toString().trim());
			}
			if(parmMap.get("lxfs")!=null && StringUtils.isNotBlank(parmMap.get("lxfs").toString())){
				criteria.andEqualTo("lxfs",parmMap.get("lxfs").toString().trim());
			}
			if(parmMap.get("jgdm")!=null && StringUtils.isNotBlank(parmMap.get("jgdm").toString())){
				//criteria.andEqualTo("JGDM",account.getJgdm());
				if (!parmMap.get("jgdm").toString().trim().startsWith("01")){
					String jgdmLike = StrUtil.removeDmZeor(parmMap.get("jgdm").toString().trim())+"%";
					criteria.andLike("jgdm",jgdmLike);
				}
			}
			PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			//result.setTotal(pageInfo.getPages());
			result.setTotal((int)pageInfo.getTotal());
			return result;
		}else{
			logger.error("AccountServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("AccountServiceImpl.queryListByPage时parmMap数据为空。");
		}
	}

	@Override
	public Account queryAccountByParm(@Param("pk")String pk,@Param("username")String username,@Param("idno")String idno,@Param("jh")String jh) throws Exception{
    	Account account = null;
		if (StringUtils.isNotBlank(pk) || StringUtils.isNotBlank(username) || StringUtils.isNotBlank(idno) || StringUtils.isNotBlank(jh) ){
			account = new Account();
			account.setPk(StringUtils.isNotBlank(pk)?pk:null);
			account.setUsername(StringUtils.isNotBlank(username)?username:null);
			account.setIdno(StringUtils.isNotBlank(idno)?idno:null);
			account.setJh(StringUtils.isNotBlank(jh)?jh:null);

			return queryAsObject(account);
		}else {
			logger.error("AccountServiceImpl.queryAccountByParme时数据为空。");
			throw new AppRuntimeException("AccountServiceImpl.queryAccountByParm时数据为空。");
		}
	}

	/**
	 * @see AccountService#queryRoleListByPage(String)
	 */
	@Override
	public List<Map<String,String>> queryRoleListByPage(String userPk) throws  Exception{
		List list = null;
		if (StringUtils.isNotBlank(userPk)){
			list = accountMapper.queryRoleListByPage(userPk);
			return list;
		}else{
			logger.error("AccountServiceImpl.queryRoleListByPage时userPk数据为空。");
			throw new AppRuntimeException("AccountServiceImpl.queryRoleListByPage时userPk数据为空。");
		}
	}

	/**
	 * @see AccountService#updateGrantRole(String, String)
	 */
	@Override
	public int updateGrantRole(String userPk,String checkedRoles) throws Exception{
		accountMapper.deleteUserRoleByUserPk(userPk);
		if(StringUtils.isNotBlank(checkedRoles)){
			String[] roles = checkedRoles.split(",");
			if (roles!=null && roles.length>0){
				List<Map<String,String>> list = new ArrayList<>();
				Map<String,String> map = null;
				for (int i=0;i<roles.length;i++){
					map = new HashMap<>();
					map.put("roleId",roles[i]);
					map.put("userPk",userPk);
					list.add(map);
				}
				return accountMapper.insertBatchUserRole(list);
			}
		}
		return 0;
	}

    
}
